package br.pucrs.lognplay.job;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import br.pucrs.lognplay.entity.LogSource;
import br.pucrs.lognplay.repository.LogSourceRepository;
import br.pucrs.lognplay.repository.RepositoryException;
import br.pucrs.lognplay.repository.RepositoryManager;

public class DynamicIndexerJob implements Job {

	private static final Logger logger = Logger.getLogger(DynamicIndexerJob.class);

	public static final String CLIENT_ID_PARAMETER = "CLIENT_ID";

	public static final String DYNAMIC_VIEW_ID_PARAMETER = "DYNAMIC_VIEW_ID";

	public static final String LOG_PATH = "/var/log/lognplay/";

	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		try {
			String clientId = jobExecutionContext.getJobDetail().getJobDataMap().getString(CLIENT_ID_PARAMETER);
			String dynamicViewId = jobExecutionContext.getJobDetail().getJobDataMap().getString(DYNAMIC_VIEW_ID_PARAMETER);

			RepositoryManager.beginTransaction();
			LogSourceRepository logSourceRepository = RepositoryManager.getLogSourceRepository();
			List<LogSource> logSources = logSourceRepository.listByClientId(clientId);
			RepositoryManager.commitTransaction();

			ElasticSearchClient esClient = new ElasticSearchClient();
			esClient.startClient();
			esClient.setBufferSize(100);
			esClient.setType("logmsg");
			esClient.setIndexName(dynamicViewId.toLowerCase().replaceAll("-", ""));

			for (LogSource logSource : logSources) {
				try {
					String fileName = logSource.getId().toLowerCase().replace("-", "") + ".log.1";
					String filePath = LOG_PATH + fileName;
					File file = new File(filePath);
					if (file.exists()) {
						logger.trace("indexing file : " + filePath);
						BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
						String line = bufferedReader.readLine();
						while (line != null) {
							esClient.put(line);
							logger.trace(line);
							line = bufferedReader.readLine();
						}
						bufferedReader.close();
						logger.trace("removing file: " + file.getPath());
						file.delete();
					}
				} catch (Exception e) {
					logger.error(e);
				}
			}
			esClient.stopClient();
		} catch (RepositoryException e) {
			logger.error(e);
		}
	}
}
